package vtt.android.lichphatsongbongda.fragments;

import java.util.ArrayList;
import java.util.List;

import mobi.mclick.ad.AdsRequest;
import mobi.mclick.ad.AdsView;

import vtt.android.library.utils.VttGA;
import vtt.android.library.utils.VttUtils;
import vtt.android.lichphatsongbongda.R;
import vtt.android.lichphatsongbongda.adapters.RssAdapter;
import vtt.android.lichphatsongbongda.dialogs.DialogManager;
import vtt.android.lichphatsongbongda.entities.CommonHashMap;
import vtt.android.rsslib.RssFeed;
import vtt.android.rsslib.RssItem;
import vtt.android.rsslib.RssReader;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.LinearLayout;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;

import com.google.android.gms.ads.AdView;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.listener.PauseOnScrollListener;
import com.twotoasters.jazzylistview.JazzyHelper;
import com.twotoasters.jazzylistview.JazzyListView;

/**
 * A placeholder fragment containing a simple view.
 */
public abstract class BaseTinTheThaoFragment extends BaseFragment {

    protected static final String ARG_SECTION_NUMBER = "SECTION_NUMBER";
    protected static final String KEY_TRANSITION_EFFECT = "transition_effect";

    protected OnItemSelectedListener listener;
    protected ParseTask parseTask;
    protected JazzyListView mListview;
    protected RssAdapter adapter;
    protected int mPageIndex = 0;
    protected String[] mRssResourceList;

    // item list
    protected List<RssItem> mItemList;
    // parent activity
    protected Activity mParentAct;

    protected int mCurrentTransitionEffect = JazzyHelper.FLIP;
    protected View mProgressBar;
    protected ImageView mBgImage;
    
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

        mParentAct = activity;
        if (activity instanceof OnItemSelectedListener) {
            listener = (OnItemSelectedListener) activity;
        } else {
            throw new ClassCastException(activity.toString()
                    + " must implemenet BaseTinTheThaoFragment.OnItemSelectedListener");
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO
        // setRetainInstance(true);
        
        mRssResourceList = getRssResoureList();
        
        mItemList = new ArrayList<RssItem>();
        adapter = new RssAdapter(mParentAct, mItemList);
        adapter.setShowHeader(isShowHeader());
        mPageIndex = 0;
        updateListContent(mRssResourceList[mPageIndex]);
    }
    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        log.d("VTT>>> " + "onCreateView");

        View rootView = inflater.inflate(R.layout.fragment_tinthethao, container, false);

        mBgImage = (ImageView) rootView.findViewById(R.id.img_bacground);
        mBgImage.setImageResource(CommonHashMap.getRandomBackgroundId());

        mListview = (JazzyListView) rootView.findViewById(R.id.listview_rss);
        mListview.setAdapter(adapter);
        mListview.setOnScrollListener(new PauseOnScrollListener(ImageLoader.getInstance(), true, true, onScrollListener));
        mListview.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                RssItem item = (RssItem) adapter.getItem(position);
                listener.onRssItemSelected(item.getLink());
            }
        });

        if (savedInstanceState != null) {
            mCurrentTransitionEffect = savedInstanceState.getInt(KEY_TRANSITION_EFFECT, mCurrentTransitionEffect);
        }

        if(Build.VERSION.RELEASE.contains("4.4.4")){
            mCurrentTransitionEffect = JazzyHelper.STANDARD;
        }
        
        setupJazziness(mCurrentTransitionEffect);

        // Look up the AdView as a resource and load a request.
//        AdView adView = (AdView) rootView.findViewById(R.id.adView);
//        loadAdmob(adView);
        /*tạo AdsView*/
        AdsView adsView = new AdsView(getActivity());
        LinearLayout layout = (LinearLayout) rootView.findViewById(R.id.adsLayout);
        layout.addView(adsView);
        /*load quảng cáo*/
        adsView.loadAds(new AdsRequest());
        // init progress bar
        mProgressBar = rootView.findViewById(R.id.progressBar1);

        return rootView;
    }

    @Override
    public void onStart() {
        super.onStart();
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        menu.clear();
        inflater.inflate(R.menu.main, menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        log.d("VTT>>> onOptionsItemSelected BaseTinTheThaoFragment ");
        switch (item.getItemId()) {
        case R.id.action_refresh:

            if (!VttUtils.checkNetworkConnection(mParentAct)) {
                mDialogManager.showCommonDialog(DialogManager.DIALOG_TYPE_INFOR,
                        getString(R.string.msg_title_notice), getString(R.string.msg_network_error), null);
                return true;
            }
            // show progress bar
            // mProgressBar.setVisibility(View.VISIBLE);
            // change background for listview
            mBgImage.setImageResource(CommonHashMap.getRandomBackgroundId());
            /*if(mParentAct instanceof LichPhatSongActivity){
                ((LichPhatSongActivity)mParentAct).changeBackground();
            }*/
            
            // reset list
            mPageIndex = 0;
            mItemList.clear();
            adapter.clear();
            adapter.notifyDataSetChanged();
            parseTask = null;

            updateListContent(mRssResourceList[mPageIndex]);

            break;

        case R.id.action_menu_rate_app:
            VttGA.sendEvent(mParentAct, "BaseTinTheThaoFragment", "Gop Y", "", 0);
            VttUtils.openGooglePlayMarket(mParentAct, mParentAct.getPackageName());
            break;

        default:
            break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt(KEY_TRANSITION_EFFECT, mCurrentTransitionEffect);
    }

    private void setupJazziness(int effect) {
        mCurrentTransitionEffect = effect;
        mListview.setTransitionEffect(mCurrentTransitionEffect);
    }

    /**
     * update list data
     * 
     * @param rssUrl
     */
    public void updateListContent(String rssUrl) {
        if(getActivity() == null){
            return;
        }
        
        log.d("VTT>>> " + "updateListContent " + rssUrl);
        if (parseTask == null) {
            // show progress
            if(mProgressBar != null && !mProgressBar.isShown()){
                mProgressBar.setVisibility(View.VISIBLE);
            }
            parseTask = new ParseTask();
            try {
                parseTask.execute(rssUrl);
            } catch (Exception e) {
                VttGA.sendException(mParentAct, e.getMessage() + " ; url " + rssUrl);
            }
        }
    }

    /**
     * update list item
     * @param result
     */
    protected abstract void updateListData(List<RssItem> result);
//    {
//        if(result != null && result.size() > 0){
//            for (int i = 0; i < result.size(); i++) {
//                if (i % 7 == 0) {
//                    RssItem adItem = new RssItem();
//                    adItem.setTitle(RssAdapter.SHOW_ADMOB);
//                    mItemList.add(adItem);
//                }
//                mItemList.add(result.get(i));
//            }
//        }
//    };

    // add event scroll listener
    OnScrollListener onScrollListener = new OnScrollListener() {
        @Override
        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
            // Log.v("TEST", "VTT>>> onScroll firstVisibleItem " + firstVisibleItem + "; visibleItemCount "
            // + visibleItemCount + "; totalItemCount " + totalItemCount);
            if ((firstVisibleItem + visibleItemCount + 1) >= totalItemCount) {
                // check next page
                if (mPageIndex < mRssResourceList.length) {
//                    if((System.currentTimeMillis() - startTime ) < 300){
//                        return;
//                    }
//                    startTime = System.currentTimeMillis();
                    updateListContent(mRssResourceList[mPageIndex]);
                }
            }
        }

        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {
            
        }
    };

    private class ParseTask extends AsyncTask<String, Void, ArrayList<RssItem>> {
        @Override
        protected void onPreExecute() {

            // TODO text image cache size
            /*
             * int sumbyte = 0; MemoryCache memoryCache = ImageLoader.getInstance().getMemoryCache(); for (String key :
             * memoryCache.keys()) { Bitmap bitmap = memoryCache.get(key); log.d("VTT>>> bitmap.getByteCount() " +
             * bitmap.getByteCount()); sumbyte += bitmap.getByteCount(); } log.d("VTT>>> sumbyte " + sumbyte);
             */

            // check network
            if (!VttUtils.checkNetworkConnection(mParentAct)) {
                mDialogManager.showCommonDialog(DialogManager.DIALOG_TYPE_INFOR, getString(R.string.msg_title_notice),
                        getString(R.string.msg_network_error), null);
            }
            super.onPreExecute();
        }

        @Override
        protected ArrayList<RssItem> doInBackground(String... params) {
            log.d("VTT>>> " + "doInBackground");
            ArrayList<RssItem> list = new ArrayList<RssItem>();
            RssFeed myFeed = null;
            String url = params[0];
            try {
                RssReader rssReader = RssReader.getInstance();
                myFeed = rssReader.read(url);
                myFeed.mRssLink = url;
                list = myFeed.getRssItems();
            } catch (Exception e) {
                // VttGA.sendException(mParentAct, "GA doInBackground : " + e.getMessage());
                e.printStackTrace();
            }
            return list;
        }

        @Override
        protected void onPostExecute(final ArrayList<RssItem> result) {
            log.d("VTT>>> " + "onPostExecute");
            try {
                mParentAct.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        
                        if (mPageIndex == 0) {
                            mItemList.clear();
                        } 
                        
                        updateListData(result);

                        adapter.notifyDataSetChanged();
                        parseTask = null;
                    }
                });
            } catch (Exception e) {
                // VttGA.sendException(mParentAct,"GA onPostExecute error : " + e.getMessage());
                e.printStackTrace();
            }
            mPageIndex++;
            mProgressBar.setVisibility(View.GONE);
        }
    }
    
    public interface OnItemSelectedListener {
        public void onRssItemSelected(String link);
    }
    
    /**
     * @return rss resource list
     */
    public abstract String[] getRssResoureList();
    
    /**
     * need to override for allowing or not show header
     * @return true: allow show header, false for otherwise
     */
    public abstract boolean isShowHeader();
}